<!--
 * @Date: 2022-03-30 16:46:42
 * @Author: 陶子
 * @LastEditTime: 2023-06-09 17:06:07
 * @FilePath: \jk_one-stop_pc\src\views\dashboard\waiterApply.vue
 * @pageName: 这是--(待处理申请)--页面
-->
<template>
  <div class="pagebox">
    <crumbs @goBack="goBack" :superiorMenu="['首页']" currentMenu="待处理申请" style="margin-bottom: 12px"></crumbs>
    <a-card :bordered="false" size="small" style="height: 100%">
      <a-button @click="showFilter = true" icon="filter" style="margin-bottom: 24px"
        >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
      >
      <a-table
        row-key="id"
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        :scroll="{ x: computedX, y: 'calc(100vh - 300px)' }"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          columnTitle: ' ',
          onChange: onSelectChange,
        }"
      >
        <!-- 筛选 -->
        <!-- 选择搜索 -->
        <div slot="selectDropdown" class="searchWorkOreder">
          <a-select
            mode="multiple"
            placeholder="请选择"
            allowClear
            style="width: 188px"
            v-model="selectType"
            @change="changeSelect"
          >
            <a-select-option v-for="(item, i) in applyTypeList" :key="i" :value="item.procCode">{{
              item.entityName
            }}</a-select-option>
          </a-select>
          <a-button type="primary" style="width: 80px; margin-left: 20px; display: block" @click="getData">
            搜索
          </a-button>
        </div>
        <!-- 人员选择 -->
        <div slot="selectPeople" class="searchWorkOreder">
          <j-select-user-by-dep
            @changeRow="userFilter"
            v-model="userIds"
            :limit="5"
            :seldep="true"
            :modalWidth="1000"
            :multi="true"
          ></j-select-user-by-dep>
          <a-button type="primary" style="width: 80px; margin-left: 20px; display: block" @click="getData">
            搜索
          </a-button>
        </div>
        <a-icon
          slot="peopleIcon"
          slot-scope="filtered"
          type="filter"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
        <!-- 插槽显示 -->
        <span
          slot="applyNo"
          class="pubColor"
          slot-scope="text, record"
          @click="allKindsOfDetail(record)"
          :title="record.applyNo"
          >{{ record.applyNo }}</span
        >
        <!-- 操作 -->
        <span slot="actions" slot-scope="text, record">
          <span class="pubColor" @click="acctionBtn(record, '0')">同意</span>
          <a-divider type="vertical" />
          <span class="pubColor" @click="acctionBtn(record, '1')">拒绝</span>
        </span>
      </a-table>
    </a-card>
    <div class="uni-card pagination-contian" :style="{ left: collapsed ? '219px' : '90px' }">
      <div class="check-contain">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span class="pubColor" style="margin: 0 16px 0 24px" @click="batchAction(0)">同意</span>
        <span class="pubColor" style="margin: 0 16px 0 0" @click="batchAction(1)">拒绝</span>
        <span>
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span class="pubColor" @click="clearArr" style="margin: 0 10px">清空</span>
        </span>
      </div>
      <div class="page-contain">
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <operation ref="operation" v-if="showModal" @resultStatus="resultStatus" />
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">
          筛选 <span class="filter-num">{{ filteredNums }}</span>
        </div>
        <div class="uni-card" v-if="filteredNums > 0" style="background: #fff">
          <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" style="float: right" />
            </span>
          </div>
        </div>
        <div style="overflow-y: scroll; flex: 1; padding: 0">
          <div class="uni-card" style="background: #fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="申请类型">
                <a-select
                  mode="multiple"
                  placeholder="请选择"
                  allowClear
                  style="width: 100%"
                  v-model="selectType"
                  @change="changeSelect"
                >
                  <a-select-option v-for="(item, i) in applyTypeList" :key="i" :value="item.procCode">{{
                    item.entityName
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="发起人">
                <j-select-user-by-dep
                  @changeRow="userFilter"
                  v-model="userIds"
                  :limit="5"
                  :seldep="true"
                  :modalWidth="1000"
                  :multi="true"
                ></j-select-user-by-dep>
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <applyDeliverDetail ref="applyDeliverDetail"></applyDeliverDetail>
    <applyPayDetail ref="applyPayDetail"></applyPayDetail>
    <receiptDetail ref="receiptDetail"></receiptDetail>
    <!-- <purchaseDetail ref="purchaseDetail"></purchaseDetail> -->
    <supplierDetail ref="supplierDetail"></supplierDetail>
    <!-- <qualifiedInputDetail ref="qualifiedInputDetail"></qualifiedInputDetail> -->
    <addMaterialRequisitionDetail ref="addMaterialRequisitionDetail"></addMaterialRequisitionDetail>
    <materialRequisitionDetail ref="materialRequisitionDetail"></materialRequisitionDetail>
    <qualityDetail ref="qualityDetail"></qualityDetail>
    <recordDetail ref="recordDetail"></recordDetail>
    <executionDetail ref="executionDetail"></executionDetail>
    <returnMaterialDetail ref="returnMaterialDetail"></returnMaterialDetail>
    <salesContractDetail ref="salesContractDetail"></salesContractDetail>
    <customerDetail ref="customerDetail"></customerDetail>
    <goodsManagementDetail ref="goodsManagementDetail"></goodsManagementDetail>
    <warehouseDetail ref="warehouseDetail"></warehouseDetail>
    <stockAllocationDetail ref="stockAllocationDetail"></stockAllocationDetail>
    <repairDetail ref="repairDetail"></repairDetail>
    <stockCheckDetail ref="stockCheckDetail"></stockCheckDetail>
  </div>
</template>
<script>
import { waiterDealApi, getProcDictList } from '@/api/erpApi'
import crumbs from '@/components/crumbs.vue'
import operation from '@/components/examine/operation'
import { mapState } from 'vuex'
let columns = [
  {
    title: '申请单号',
    dataIndex: 'applyNo',
    ellipsis: true,
    width: '20%',
    scopedSlots: {
      customRender: 'applyNo',
    },
  },
  {
    title: '申请标题',
    dataIndex: 'title',
    ellipsis: true,
    width: '20%',
  },
  {
    title: '申请类型',
    dataIndex: 'typeName',
    ellipsis: true,
    width: '15%',
    searchKey: 'procCode',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'peopleIcon',
      customRender: 'procCode',
    },
  },
  {
    title: '发起人',
    dataIndex: 'launchUserName',
    ellipsis: true,
    width: '10%',
    scopedSlots: {
      filterDropdown: 'selectPeople',
      filterIcon: 'peopleIcon',
      customRender: 'launchUserName',
    },
  },
  {
    title: '发起时间',
    dataIndex: 'flowLaunchTime',
    ellipsis: true,
    width: '20%',
  },
  {
    title: '操作',
    width: '15%',
    dataIndex: 'actions',
    scopedSlots: { customRender: 'actions' },
  },
]

export default {
  components: {
    crumbs,
    operation,
    applyDeliverDetail: (resolve) => require(['@/views/apply/applyDeliverDetail'], resolve),
    applyPayDetail: (resolve) => require(['@/views/apply/applyPayDetail'], resolve),
    receiptDetail: (resolve) => require(['@/views/procurementManagement/purchaseContract/receiptDetail'], resolve),
    // purchaseDetail: resolve => require(['@/views/procurementManagement/purchaseContract/purchaseDetail.vue'], resolve),
    supplierDetail: (resolve) =>
      require(['@/views/procurementManagement/supplierManagement/supplierDetail.vue'], resolve),
    // qualifiedInputDetail: (resolve) => require(['@/views/workManagement/qualifiedInput/qualifiedInputDetail'], resolve),
    addMaterialRequisitionDetail: (resolve) =>
      require(['@/views/workManagement/addMaterialRequisition/addMaterialRequisitionDetail'], resolve),
    materialRequisitionDetail: (resolve) =>
      require(['@/views/workManagement/materialRequisition/materialRequisitionDetail'], resolve),
    qualityDetail: (resolve) => require(['@/views/qualityManagement/qualityRecord/qualityDetail'], resolve),
    recordDetail: (resolve) => require(['@/views/workManagement/reportRecord/recordDetail'], resolve),
    executionDetail: (resolve) => require(['@/views/workManagement/defectsDeal/executionDetail'], resolve),
    returnMaterialDetail: (resolve) => require(['@/views/workManagement/returnMaterial/returnMaterialDetail'], resolve),
    salesContractDetail: (resolve) => require(['@/views/salesManagement/salesContract/salesContractDetail'], resolve),
    customerDetail: (resolve) => require(['@/views/salesManagement/customerManagement/customerDetail'], resolve),
    goodsManagementDetail: (resolve) =>
      require(['@/views/warehouseManagement/goodsManagement/goodsManagementDetail'], resolve),
    warehouseDetail: (resolve) => require(['@/views/warehouseManagement/warehouse/warehouseDetail'], resolve),
    stockAllocationDetail: (resolve) =>
      require(['@/views/warehouseManagement/stockAllocation/stockAllocationDetail'], resolve),
    repairDetail: (resolve) => require(['@/views/baseManagement/maintain/repairDetail'], resolve),
    stockCheckDetail: (resolve) => require(['@/views/warehouseManagement/stockCheck/stockCheckDetail'], resolve),
  },
  data() {
    return {
      columns,
      tableData: [],
      current: 1,
      total: 0,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      showModal: false,
      selectedRowKeys: [],
      chooseArr: [],
      listIndeterminate: false,
      listCheckAll: false,
      // 筛选
      showFilter: false,
      userIds: '',
      userNames: '',
      filterForm: {
        initiatorIds: '',
        procCode: '',
      },
      filteredFormLable: {
        initiatorIds: '发起人',
        procCode: '类型',
      },
      applyTypeList: [],
      selectType: undefined,
    }
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsedAno,
    }),
    computedX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width)
      }

      return xnum
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key]) {
          nums += 1
        }
      }
      return nums
    },
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (key == 'initiatorIds') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.userNames,
            key,
          })
        } else if (key == 'procCode') {
          let arr = []
          let vals = this.filterForm[key].split(',')
          for (let i = 0; i < vals.length; i++) {
            const val = vals[i]
            for (let j = 0; j < this.applyTypeList.length; j++) {
              const type = this.applyTypeList[j]
              if (val == type.procCode) {
                arr.push(type.entityName)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: arr.join(','),
            key,
          })
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        }
      }
      return list
    },
  },
  created() {
    getProcDictList().then((res) => {
      this.applyTypeList = res.result || []
    })
    this.getData()
  },
  methods: {
    changeSelect(v) {
      this.filterForm.procCode = v.join(',')
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.getData()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (key == 'initiatorIds') {
        this.userIds = ''
        this.userNames = ''
        this.filterForm[key] = ''
      } else {
        this.filterForm[key] = ''
      }
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        initiatorIds: '',
        procCode: '',
      }
      this.userIds = ''
      this.userNames = ''
      this.selectType = undefined
      this.getData()
    },
    // 选人
    userFilter(v, row) {
      console.log(this.userIds)
      let uIds = []
      let uNames = []
      if (row.length > 0) {
        row.forEach((u) => {
          uIds.push(u.id)
          uNames.push(u.realname)
        })
        this.filterForm.initiatorIds = uIds.join(',')
        this.userNames = uNames.join(',')
        this.getData()
      } else {
        this.filterForm.initiatorIds = ''
        this.userNames = ''
      }
    },
    allKindsOfDetail(row) {
      let detailUrl = ''
      switch (row.type) {
        case 'ERP_SHIPPING_APPLY': //申请发货——对应详情
          detailUrl = 'applyDeliverDetail'
          break
        case 'ERP_PURCHASE_TASK_APPLY': //申请采购——对应详情
          detailUrl = 'applyPayDetail'
          break
        case 'ERP_PURCHASE_SIGN_ORDER': //采购合同签收——对应详情
          detailUrl = 'receiptDetail'
          break
        case 'ERP_PURCHASE_CONTRACT': //新建采购合同——对应详情
          detailUrl = 'purchaseDetail'
          break
        case 'ERP_SUPPLIER': //新建供应商——对应详情
          detailUrl = 'supplierDetail'
          break
        case 'MESS_QUALIFIED_INBOUND_APPLY': //合格品申请入库——对应详情
          detailUrl = 'qualifiedInputDetail'
          break
        case 'MESS_REMEDY_MATERIAL_APPLY': //申请补料——对应详情
          detailUrl = 'addMaterialRequisitionDetail'
          break
        case 'MESS_RECEIVE_MATERIAL_APPLY': //申请领料——对应详情
          detailUrl = 'materialRequisitionDetail'
          break
        case 'MESS_TASK_REPORT_WORK_APPLY_FOR_QUALITY': //质检报工——对应详情
          detailUrl = 'qualityDetail'
          break
        case 'MESS_TASK_REPORT_WORK_APPLY_FOR_PRODUCT': //生产报工——对应详情
          detailUrl = 'recordDetail'
          break
        case 'MESS_SCRAP_INBOUND_APPLY': //申请报废入库——对应详情
          detailUrl = 'executionDetail'
          break
        case 'MESS_RETURN_MATERIAL_APPLY': //申请退料——对应详情
          detailUrl = 'returnMaterialDetail'
          break
        case 'ERP_SALE_CONTRACT': //新建销售合同——对应详情
          detailUrl = 'salesContractDetail'
          break
        case 'ERP_CUSTOMER': //新建客户——对应详情
          detailUrl = 'customerDetail'
          break
        case 'WMS_GOODS': //新建物品——对应详情
          detailUrl = 'goodsManagementDetail'
          break
        case 'WMS_WAREHOUSE': //新建仓库——对应详情
          detailUrl = 'warehouseDetail'
          break
        case 'WMS_STOCK_ALLOT': //库存调拨——静态路由
          detailUrl = 'stockAllocationDetail'
          break
        case 'MESS_DEVICE_REPAIR': //设备管理——故障报修
          detailUrl = 'repairDetail'
          break
        case 'WMS_WAREHOUSE_INVENTORY': //仓库管理-库存盘点详情
          detailUrl = 'stockCheckDetail'
          break
      }
      let paramsObj = null
      if (row.type == 'ERP_SHIPPING_APPLY') {
        paramsObj = {
          applyNo: row.applyNo,
        }
      } else {
        paramsObj = row.entityId
      }
      this.$refs[detailUrl].initDetail(paramsObj)
      // this.$openWay(this, false, detailUrl, paramsObj)
    },
    // 获取审批结果
    resultStatus(v) {
      if (v) {
        this.current = 1
        this.clearArr()
        this.getData()
      }
      this.showModal = false
    },
    /* 面包屑返回 */
    goBack() {
      this.$router.go(-1)
    },
    // 操作
    acctionBtn(row, type) {
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.operation.getData(true, row.id, Number(type)) //true(开启弹窗)，'aaa111'(流程id)，0(0同意，1拒绝)
      })
    },
    getData() {
      let params = {
        pageNo: this.current,
        pageSize: this.pageSize,
        ...this.filterForm,
        queryType: 'needToExecute',
      }
      waiterDealApi(params).then((res) => {
        if (res.success) {
          if (res.result.total) {
            this.total = res.result.total
          } else {
            this.total = 0
          }
          let copyArr = JSON.parse(JSON.stringify(res.result.records))
          for (let item of copyArr) {
            for (let each in item) {
              if (!item[each] && item[each] != 0) {
                item[each] = '-'
              }
            }
          }
          this.tableData = copyArr
          this.checkBoxStatus()
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    // 批量审批
    batchAction(num) {
      if (this.selectedRowKeys.length > 0) {
        this.showModal = true
        this.$nextTick(() => {
          this.$refs.operation.getData(true, this.selectedRowKeys.join(','), num) //true(开启弹窗)，'aaa111'(流程id)，0(0同意，1拒绝)
        })
      } else {
        this.$antdMessage.info('请先选择数据')
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.chooseArr = this.chooseArr.concat(selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.tableData) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log()
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.chooseArr.push(item)
        }
      } else {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    clearArr(type) {
      this.selectedRowKeys = []
      this.chooseArr = []
      if (type) {
        this.getData()
      } else {
        this.checkBoxStatus()
      }
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.getData()
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize
      this.current = 1
      this.getData()
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.table-operations {
  margin-bottom: 16px;
}

.table-operations > button {
  margin-right: 8px;
}

.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}
.pagebox {
  /deep/ .ant-card-body {
    height: calc(100vh - 174px);
    overflow: hidden;
    padding: 20px 16px;
  }
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.modalTopBox {
  .flex(flex-start, center);
  margin-bottom: 8px;
  span {
    margin-left: 16px;
    display: block;
    overflow: hidden;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    font-size: 16px;
    line-height: 1.4;
  }
}
.bigFont {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.78);
  box-sizing: border-box;
  padding-left: 12px;
  margin-bottom: 8px;
  font-weight: 600;
}
.smallFont {
  font-size: 14px;
  box-sizing: border-box;
  padding-left: 12px;
}
</style>
